﻿using System;
using ASPNETVN.PORTAL.Components.Helpers;
using ASPNETVN.PORTAL.Components.Security;
using ASPNETVN.PORTAL.Components.UI;
using ASPNETVN.PORTAL.Modules.DOCUMENT.Components;
using ASPNETVN.PORTAL.Components.Share;
using Type=ASPNETVN.PORTAL.Modules.DOCUMENT.Components.Type;
using System.Web.UI.WebControls;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.IO;

namespace ASPNETVN.PORTAL.Modules.DOCUMENT.Controls
{
    public partial class AddEditItemWithMultipleCategories : ApproveItemControl
    {
        protected override void OnInit(EventArgs e)
        {
            this.ButtonUpdate = btnUpdate;
            this.ButtonCancel = btnCancel;

            this.Update += AddEditItem_Update;
            base.OnInit(e);
        }

        private IList<ListItem> GetSelectedCategories()
        {
            IList<ListItem> selectedCategories = new List<ListItem>();

            foreach (Control control in PanelCategories.Controls)
            {
                if (typeof(CheckBoxList) == control.GetType())
                {
                    CheckBoxList chk = control as CheckBoxList;
                    foreach (ListItem i in chk.Items)
                    {
                        if (i.Selected)
                        {
                            selectedCategories.Add(i);
                        }
                    }
                }
            }
            return selectedCategories;
        }

        private void BuildCheckBoxListControl()
        {
            IList<Category> allCategories = new List<Category>();

            // Administrators Role.
            if (PortalSecurity.IsInRole("1"))
            {
                allCategories = Category.SelectCollectionAll(this.ModuleID);
            }
            else
            {
                allCategories = Category.SelectBy_UserID_ModuleID(PortalSecurity.CurrentUser.Identity.ID, this.ModuleID);
            }
            IList<Category> topCategories = allCategories.Where(x => x.ParentID == 0).OrderBy(x => x.Title).ToList();

            foreach (Category topCategory in topCategories)
            {
                Label label = new Label();
                label.EnableViewState = true;
                label.ID = "Label_" + topCategory.ID;
                label.Text = topCategory.Title;
                label.Font.Bold = true;
                PanelCategories.Controls.Add(label);

                CheckBoxList checkboxlist = new CheckBoxList();
                checkboxlist.EnableViewState = true;
                checkboxlist.ID = "CheckBoxList_" + topCategory.ID;
                IList<Category> childCategories = allCategories.Where(x => x.ParentID == topCategory.ID).OrderBy(x => x.Title).ToList();
                foreach (Category childCategory in childCategories)
                {
                    checkboxlist.Items.Add(new ListItem(childCategory.Title, childCategory.ID.ToString()));
                }
                PanelCategories.Controls.Add(checkboxlist);
            }
        }

        protected void UploadAttachment(IList<int> itemIDs)
        {
            // Lưu tập tin.
            string fileUrl = string.Empty;
            int fileSize = FileUploadAttachment.PostedFile.ContentLength;
            byte[] buffer = new byte[0];
            string storageType = this.Settings["StorageType"].ToString().ToUpper();

            if (storageType.Equals("DATABASE"))
            {
                Stream stream = FileUploadAttachment.PostedFile.InputStream;
                buffer = new byte[FileUploadAttachment.PostedFile.ContentLength];

                try
                {
                    stream.Read(buffer, 0, fileSize);
                }
                finally
                {
                    stream.Close();
                }
                fileUrl = "#";
            }
            else if (storageType.Equals("FILE"))
            {
                string physicalDirectory = Server.MapPath("~/Uploads/" + this.ModuleID);
                // Tạo thư mục để chứa tập tin.
                if (Directory.Exists(physicalDirectory) == false)
                {
                    Directory.CreateDirectory(physicalDirectory);
                }

                string physicalPath = physicalDirectory + "\\" + this.FileUploadAttachment.FileName;
                int i = 1;
                while (File.Exists(physicalPath))
                {
                    physicalPath = physicalDirectory + "\\" + i + "_" + this.FileUploadAttachment.FileName;
                    i++;
                }
                FileInfo fi = new FileInfo(physicalPath);
                FileUploadAttachment.SaveAs(physicalPath);
                fileUrl = "~/Uploads/" + this.ModuleID + "/" + fi.Name;
            }

            foreach (int i in itemIDs)
            {
                Attachment attachment = new Attachment();
                attachment.ModuleID = this.ModuleID;
                attachment.ItemID = i;
                attachment.StorageType = storageType;
                attachment.FileSize = fileSize;
                attachment.FileName = FileUploadAttachment.FileName;
                attachment.FileUrl = fileUrl;
                attachment.ContentType = FileUploadAttachment.PostedFile.ContentType;
                attachment.BinaryContent = buffer;
                int attachmentID = attachment.Insert();

                if (storageType.Equals("DATABASE"))
                {
                    attachment.FileUrl = HttpUrlBuilder.BuildShareUrl(this.ModuleID, attachmentID, "DownloadFile");
                    attachment.Update();
                }
            }            
        }

        void AddEditItem_Update(object sender, EventArgs e)
        {
            try
            {
                IList<ListItem> selectedCategories = this.GetSelectedCategories();
                Components.Item item = new Components.Item();
                IList<int> insertedItems = new List<int>();
                foreach (ListItem i in selectedCategories)
                {

                    item.CategoryID = Convert.ToInt32(i.Value);
                    item.TypeID = Convert.ToInt32(DropDownListType.SelectedValue);
                    item.PublisherID = Convert.ToInt32(DropDownListPublisher.SelectedValue);
                    item.Code = TextBoxCode.Text;
                    item.PublishedDate = Convert.ToDateTime(TextBoxPublishedDate.Text);
                    if (TextBoxAvailableDate.Text.Length > 0)
                    {
                        item.AvailableDate = Convert.ToDateTime(TextBoxAvailableDate.Text);
                    }
                    item.SignedBy = TextBoxSigner.Text;
                    item.Summary = TextBoxSummary.Text;
                    item.CreatedDate = DateTime.Now;
                    item.CreatedBy = PortalSecurity.CurrentUser.Identity.Email;
                    this.ItemID = item.Insert();
                    insertedItems.Add(this.ItemID);
                }
                UploadAttachment(insertedItems);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            // Upload file.

            this.ReturnToReferrerPage();

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.BuildCheckBoxListControl();
            if (IsPostBack == false)
            {
                DropDownListPublisher.DataSource = Publisher.SelectCollectionAll(this.ModuleID);
                DropDownListPublisher.DataBind();

                DropDownListType.DataSource = Type.SelectCollectionAll(this.ModuleID);
                DropDownListType.DataBind();
            }
        }
    }
}